﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;

namespace HomeFramework.Core
{
    public static class MessageMtomByteWriter
    {
        private static BufferManager Buffer = BufferManager.CreateBufferManager(0, 0);
        private static MessageEncoder getEncoder(MessageVersion version)
        {
            var m = new MtomMessageEncodingBindingElement();
            m.ReaderQuotas.MaxArrayLength = int.MaxValue;
            m.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            m.ReaderQuotas.MaxDepth = int.MaxValue;

            return m.CreateMessageEncoderFactory().Encoder;
        }

        public static byte[] MessageToBytes(Message arg, MessageVersion version)
        {
            return getEncoder(version).WriteMessage(arg, int.MaxValue, Buffer).Array;
        }

        public static Message MessageFromBytes(byte[] arg, MessageVersion version)
        {
            return getEncoder(version).ReadMessage(new ArraySegment<byte>(arg), Buffer);
        }
    }
}
